import pygame, sys, os
from panel import *

class LayerPanels(object):
    """ provide layer manage panel """
    def __init__(self):
        self.__p = {}
        
    def add(self, pan):
        if not self.__p.has_key(pan.layer):
            self.__p[pan.layer] = []
        self.__p[pan.layer].append(pan) 
    
    def update(self):
        layer = self.__p.keys()
        layer.sort() # orderly
        for ly in layer:
            for pan in self.__p[ly]:
                pan.update()
    
    def remove(self, pan):
        if self.__p.has_key(pan.layer):
            self.__p[pan.layer].remove(pan) 


class Control(object):
    """ init program, control the panels """
    WINDOW = (800, 640)
    CAPTION = 'Mini Tank'
    FPS = 50
    def __init__(self):
        super(Control, self).__init__()
        if sys.platform in ("win32", "win64"):
            os.environ["SDL_VIDEO_CENTERED"] = "1"
        pygame.init()
        self.__window = pygame.display.set_mode(Control.WINDOW)
        pygame.display.set_caption(Control.CAPTION)
        self.panels = LayerPanels()
        self.focus = []
        self.__clock = pygame.time.Clock()
        
    def start(self):
        self.start_menu()
        while 1:
            # control FPS
            self.__clock.tick(Control.FPS)
            # process keyboard
            for event in pygame.event.get():
                if event.type == pygame.QUIT: sys.exit()
            for pan in self.focus: pan.keyboard()
            # update panel
            self.panels.update()
            pygame.display.update()
    
    def register(self, pan):
        self.panels.add(pan)
        if pan.focus: self.focus.append(pan)
    
    def unregister(self, pan):
        self.panels.remove(pan)
        if pan.focus: self.focus.remove(pan)
    
    def start_menu(self):
        pan = StartMenu(self, self.__window.subsurface(pygame.Rect(((0, 0), Control.WINDOW))))
        self.register(pan)
    
    def level_begin(self, level):
        pan = LevelPanel(self, self.__window.subsurface(pygame.Rect(((0, 0), Control.WINDOW))), level)
        self.register(pan)
    
    def level_start(self, level):
        pan = GamePanel(self, self.__window.subsurface(pygame.Rect(((0, 0), Control.WINDOW))), level)
        self.register(pan)
